# !/usr/bin/env python3

import re
import hashlib
import platform
import datetime
import http.client

print ("Hello, Python " + platform.python_version() + "!")
print ("建议运行当前程序脚本，使用Python3.x!")

httpAddress = "39.105.14.222"
port = 80

#发送POST请求
def sendPost(httpUrl, content, contentType):
        #开启http链接
        conn = http.client.HTTPConnection(httpAddress, port)

        #构建请求参数
        headerdata = {
                "User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)",
                "Content-Type": contentType,
                "Connection": "Keep-Alive"
                }
        
        #发送请求
        conn.request(method="POST", url=httpUrl, body=content.encode('UTF-8'), headers = headerdata)

        #接收响应
        response = conn.getresponse().read().decode('UTF-8')
        conn.close()
        return response


#构造签名时的key排序列表
def sortParamKeyArray(params):
        keyArray = []
        for key in params.keys():
                keyArray.append(key)
        keyArray.sort()
        return keyArray


#构造签名
def makeSign(appSecret, params, content, rejectEmptyCharacters):
        signStr = appSecret
        #参数排序,适配PHP的ksort()函数
        keyArray = sortParamKeyArray(params);
        #参数拼接
        for key in keyArray:
                if key != "sign" and params[key] != "":
                        signStr += key
                        signStr += params[key]
        signStr += content
        signStr += appSecret
        #是否去掉空字符串
        if rejectEmptyCharacters:
                signStr = re.sub("\\s*", "", signStr)
        #摘要MD5
        sign = hashlib.md5()   
        sign.update(signStr.encode('utf-8'))   
        return sign.hexdigest().upper()


#构造请求参数
def makeURLParam(params):
    urlParams = ""
    for key,value in params.items():
                urlParams += "&"
                urlParams += key
                urlParams += "="
                if "timestamp" == key:
                        urlParams += value.replace(" ", "%20")
                        continue
                urlParams += value
    return urlParams.lstrip("&")


#ERP推送接口
def erpAPI(httpUrl, method, appKey, appSecret, sid, content):
        params = {
                   "method": method,
                   "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                   "format": "xml",
                   "appkey": appKey,
                   "sign_method": "md5",
                   "sid": sid
                }
        params['sign'] = makeSign(appSecret, params, content, True)
        httpUrl += "?" + makeURLParam(params);
        print ("请求地址参数：" + httpUrl);
        message = sendPost(httpUrl, content, "text/xml;charset=utf-8");
        print ("响应结果：" + message);
        return message

#推单示例
httpUrl = "/wms_api/wdt_service.php"
method = "WDT_WMS_DELIVERYORDER_CREATE"
appKey = "以实际联调人员分配为准"
appSecret = "以实际联调人员分配为准"
sid = "以实际联调人员分配为准"
# content 用实际接口的入参报文替代
content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><request><deliveryOrder><deliveryOrderCode>postman_166260538551054698</deliveryOrderCode><orderType>JYCK</orderType><warehouseCode>warehouse_sly</warehouseCode><sourcePlatformCode>TM</sourcePlatformCode><sourcePlatformName></sourcePlatformName><logisticsCode>SFHH-XX</logisticsCode><createTime>2018-10-18 13:48:52</createTime><placeOrderTime>2018-10-18 13:47:25</placeOrderTime><payTime>2018-10-18 13:47:25</payTime><operateTime>2018-10-18 13:48:52</operateTime><shopNick>postman店铺</shopNick><buyerNick>买家</buyerNick><totalAmount>120</totalAmount><gotAmount>0</gotAmount><arAmount>100</arAmount><freight>0</freight><logisticsAreaCode>标准大头笔</logisticsAreaCode><invoiceFlag>N</invoiceFlag><buyerMessage/><serviceFee>110</serviceFee><sellerMessage>客服备注</sellerMessage><printRemark>打印备注</printRemark><senderInfo><name>1</name><mobile>1</mobile><province>天津市</province><city>天津市</city><area>滨海新区</area><detailAddress>华夏金融大厦</detailAddress></senderInfo><receiverInfo><name>倚天剑</name><idType>1</idType><idNumber>12344</idNumber><mobile> 13789888477 </mobile><tel></tel><province>河北省</province><city>邯郸市</city><area>邯山区</area><zipCode/><detailAddress>邯郸科技职业学院</detailAddress></receiverInfo><invoices><invoice><type>INVOICE</type><header>嘉兴河海中控信息</header><amount>868</amount><content>内容</content><taxNumber>我是税号</taxNumber></invoice></invoices><insurance><type>保险类型</type><amount>01</amount></insurance><deliveryRequirements><deliveryType>PTPS</deliveryType></deliveryRequirements><extendProps><flag_id>10</flag_id><wdtfx_platform>YZ</wdtfx_platform></extendProps></deliveryOrder><orderLines><orderLine><orderLineNo>1</orderLineNo><ownerCode>sly</ownerCode><itemCode>iphone</itemCode><itemId>409</itemId><inventoryType>ZP</inventoryType><itemName></itemName><sourceOrderCode>postman_166260538551054698</sourceOrderCode><subSourceOrderCode></subSourceOrderCode><payNo>payNo2</payNo><planQty>3</planQty><batchCode></batchCode><actualPrice>50</actualPrice><discountAmount>01</discountAmount><retailPrice>100</retailPrice><extendProps><erpDiscountRatio>0</erpDiscountRatio><fromMask>0</fromMask><suiteName>组合装</suiteName><suiteNum>1</suiteNum><payAccount>payAccount1</payAccount></extendProps><remark>备注</remark></orderLine></orderLines><extendProps><ConsolidationCode>集包地编码</ConsolidationCode><ConsolidationName>集包地名字，这个是可以打印的</ConsolidationName></extendProps></request>"
erpAPI(httpUrl, method, appKey, appSecret, sid, content)



